package com.party.admin.web.controller.system;

import com.party.admin.biz.system.PartnerMemberBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.utils.StringUtils;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberAdministrator;
import com.party.core.model.partner.MemberPartnerPrivilege;
import com.party.core.service.member.IMemberAdministratorService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.partner.IMemberPartnerPrivilegeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wei.li
 *
 * @date 2017/9/25 0025
 * @time 11:38
 */

@Controller
@RequestMapping(value = "partner/member")
public class PartnerMemberController {

    @Autowired
    private PartnerMemberBizService partnerMemberBizService;
    @Autowired
    private IMemberPartnerPrivilegeService memberPartnerPrivilegeService;
    @Autowired
    private IMemberAdministratorService memberAdministratorService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 机构会员关系
     *
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "init")
    public AjaxResult init() throws InterruptedException {
        partnerMemberBizService.init();
        return AjaxResult.success();
    }

    /**
     * 获取合作商对应的所属者
     *
     * @param partnerId 合作商编号
     * @return
     */
    @ResponseBody
    @RequestMapping("getMemberInitiator")
    public AjaxResult getMemberInitiator(String partnerId) {
        if (StringUtils.isEmpty(partnerId)) {
            return AjaxResult.error("合作商编号不能为空");
        }
        Map<String,Object> map = new HashMap();
        List<Map<String, String>> memberAdmins = memberAdministratorService.findByPartnerId();
        List<Map<String, String>> members = memberPartnerPrivilegeService.findByPartnerId(partnerId);
        map.put("memberAdmins",memberAdmins);
        map.put("members",members);
        return AjaxResult.success(map);
    }

    /**
     * 获取管理员找合作商
     *
     * @param initiatorId 管理员编号
     * @return
     */
    @ResponseBody
    @RequestMapping("getPartnerByInitiator")
    public AjaxResult getPartnerByInitiator(String initiatorId) {
        if (StringUtils.isEmpty(initiatorId)) {
            return AjaxResult.error("管理员编号不能为空");
        }
        try {
            Map<String,Object> map = new HashMap();
            MemberAdministrator memberAdministrator = memberAdministratorService.getByMemberId(initiatorId);
            if(memberAdministrator != null){
                map.put("memberAdmin",memberAdministrator);
                return AjaxResult.success(map);
            }
            List<Map<String, String>> members = memberPartnerPrivilegeService.findByMemberId(initiatorId);
            map.put("privileges", members);
            return AjaxResult.success(map);
        } catch (Exception e) {
            logger.error("异常", e);
            return AjaxResult.error("异常");
        }
    }

    /**
     * @param initiatorIds 管理员
     * @param partnerId    合作商
     * @return
     */
    @ResponseBody
    @RequestMapping("saveInitiator")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveInitiator(String initiatorIds, String partnerId) {
        if (StringUtils.isEmpty(partnerId)) {
            return AjaxResult.error("参数不完整");
        }

        try {
            memberPartnerPrivilegeService.deleteByPartnerId(partnerId);
            if (StringUtils.isNotEmpty(initiatorIds)) {
                for (String initiatorId : initiatorIds.split(",")) {
                    MemberAdministrator byMemberId = memberAdministratorService.getByMemberId(initiatorId);
                    if(byMemberId == null){
                        MemberPartnerPrivilege partnerPrivilege = new MemberPartnerPrivilege(initiatorId, partnerId);
                        memberPartnerPrivilegeService.insert(partnerPrivilege);
                    }
                }
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存合作商权限异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存合作商权限异常");
        }
    }

    /**
     * @param initiatorId 管理员
     * @param partnerIds  合作商
     * @param adminInstitutions  管理员对应机构商是否对象全部机构：1代表是，0代表不是
     * @return
     */
    @ResponseBody
    @RequestMapping("savePartner")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult savePartner(String partnerIds, String initiatorId,String adminInstitutions) {
        if (StringUtils.isEmpty(initiatorId)) {
            return AjaxResult.error("参数不完整");
        }

        try {
            memberPartnerPrivilegeService.deleteByMemberId(initiatorId);
            int i = memberAdministratorService.deleteByMemberId(initiatorId);
            if (StringUtils.isNotEmpty(partnerIds) && "0".equals(adminInstitutions)) {
                for (String partnerId : partnerIds.split(",")) {
                    MemberPartnerPrivilege partnerPrivilege = new MemberPartnerPrivilege(initiatorId, partnerId);
                    memberPartnerPrivilegeService.insert(partnerPrivilege);
                }
            }
            if (StringUtils.isEmpty(partnerIds) && "1".equals(adminInstitutions)) {
                MemberAdministrator memberAdministrator = new MemberAdministrator(initiatorId, Integer.valueOf(adminInstitutions));
                memberAdministratorService.insert(memberAdministrator);

            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存合作商权限异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存合作商权限异常");
        }
    }
}
